# coding:UTF-8
import re
import csv
import argparse

ALL_REGX = \
    [
        [   # ("Field Name", "Log String")
            ("L2-LO UL", "LINUX-Disp_\d\s<(.*?).\d+Z>.*?L2-LO UL:\s*(\d+)\s*Bytes received in.*"),
            ("LouD", "LINUX-Disp_\d\s<(.*?).\d+Z>.*?LouD:\s*(\d+)\s*Bytes received in.*")
        ]
    ]

'''File format
┌─────────────────────────────┐
│SYSTIME│ITEM │ITEM │ITEM │...│
│TIME   │VALUE│VALUE│VALUE│...│
│.............................│
└─────────────────────────────┘
'''

class LogFileParser():
    def __init__(self, fileName):
        self.fileData = fileName.read()
        self.regex = ALL_REGX[0]
        self.fieldNames = ["Systime"]

    def logParse(self):
        allDataDict = {}
        allDataList = []
        for reg in self.regex:
            self.fieldNames.append(reg[0])
            compiledRegex = re.compile(reg[1])
            for item in compiledRegex.findall(self.fileData):
                parsedItem = []
                parsedItem.append(("Systime", item[0]))
                parsedItem.append((reg[0], item[1]))               
                if(allDataDict.has_key(item[0])):
                    allDataDict[item[0]].append((reg[0], item[1]))
                else:
                    allDataDict[item[0]] = parsedItem
        allDataList = self.sortDictValues(allDataDict)
        return allDataList

    def sortDictValues(self, dataDict):
        keys = dataDict.keys()
        keys.sort()
        return [dataDict[key] for key in keys]    
        
class OutputWriter(object):
    def __init__(self, headerRow, dataToWrite, outputFileName):
        self.headerRow = headerRow
        self.dataToWrite = dataToWrite
        self.outputFileName = outputFileName.split(".")[0]
        self.writeCsvFile()
            
    def writeCsvFile(self):
        fnWithExtension = self.outputFileName + ".csv"
        print("Writing CSV file: " + fnWithExtension)
        with open(fnWithExtension, 'wb') as csvFile:
            writer = csv.DictWriter(csvFile, self.headerRow, restval="-", extrasaction='ignore')
            writer.writeheader()
            for item in self.dataToWrite:
                row = dict(item)
                writer.writerow(row)
		      
if __name__ == "__main__":
    docstring = """
        KEY WORD PARSE
    """
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=docstring)
    req_group = parser.add_argument_group("required arguments")
    req_group.add_argument("-i", "--input", type=argparse.FileType('r'))
    req_group.add_argument("-o", "--output", required=True)
    args = parser.parse_args()
    logFileParser = LogFileParser(args.input)
    allParsedData = logFileParser.logParse()
    outputFileHeader = logFileParser.fieldNames     
    OutputWriter(outputFileHeader, allParsedData, args.output)        
        
        
        
 